package io.plus.user_interface.io.server.command.command_handler;

import drds.common.$;
import drds.common.Uuid;
import io.plus.interactive.AsynchronousSocketChannelContext;
import io.plus.interactive.Io;
import io.plus.user_interface.io.common.SessionContext;
import io.plus.user_interface.io.common.Status;
import io.plus.user_interface.io.common.io;
import io.plus.user_interface.io.common.message.MessageHelper;
import io.plus.user_interface.io.common.packet.Command;
import io.plus.user_interface.io.common.packet.Group;
import io.plus.user_interface.io.common.packet.User;
import io.plus.user_interface.io.common.packet.login.LoginRequestMessage;
import io.plus.user_interface.io.common.packet.login.LoginResponseMessage;
import io.plus.user_interface.io.common.protocol.PacketImpl;
import io.plus.user_interface.io.common.utils.JsonKit;
import io.plus.user_interface.io.server.command.AbstractCommandHandler;
import io.plus.user_interface.io.server.command.CommandManager;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 登录消息命令处理器
 */
@Slf4j
public class LoginReqHandler extends AbstractCommandHandler {
    public static final Map<String, User> tokenToUserMap = new HashMap<>();

    /**
     * 初始化绑定或者解绑群组;
     */
    public void bindUnbindGroup(AsynchronousSocketChannelContext asynchronousSocketChannelContext, User user) throws Exception {
        String userId = user.getId();
        List<Group> groups = user.getGroups();
        if (groups != null) {
            boolean isStore = true;
            MessageHelper messageHelper = null;
            List<String> groupIds = null;
            if (isStore) {
                messageHelper = userConfiguration.getMessageHelper();
                groupIds = messageHelper.getGroups(userId);
            }
            //绑定群组
            for (Group group : groups) {
                if (isStore && groupIds != null) {
                    groupIds.remove(group.getId());
                }
                PacketImpl groupPacket = new PacketImpl(Command.join_group_request, JsonKit.toJsonBytes(group));
                try {
                    JoinGroupCommandHandler joinGroupReqHandler = CommandManager.getCommand(Command.join_group_request, JoinGroupCommandHandler.class);
                    joinGroupReqHandler.bindGroup(groupPacket, asynchronousSocketChannelContext);
                } catch (Exception e) {
                    log.error(e.toString(), e);
                }
            }
            if (isStore && groupIds != null) {
                for (String groupId : groupIds) {
                    messageHelper.getBindListener().onAfterGroupUnbind(asynchronousSocketChannelContext, groupId);
                }
            }
        }
    }

    @Override
    public Command command() {
        return Command.login_request;
    }

    @Override
    public PacketImpl handler(PacketImpl packet, AsynchronousSocketChannelContext asynchronousSocketChannelContext) throws Exception {
        if (packet.getBody() == null) {
            Io.remove(asynchronousSocketChannelContext, "body is null");
            return null;
        }

        SessionContext sessionContext = (SessionContext) asynchronousSocketChannelContext.getAttribute();
        LoginRequestMessage loginRequestMessage = JsonKit.toBean(packet.getBody(), LoginRequestMessage.class);

        String loginname = loginRequestMessage.getLoginname();
        String password = loginRequestMessage.getPassword();

        String token = sessionContext.getToken();
        User user;
        LoginResponseMessage loginResponseMessage;
        if (!$.isNullOrEmpty((token))) {
            user = tokenToUserMap.get(token);
            if (user == null) {
                user = new User();
                user.setId(token);
                tokenToUserMap.put(token, user);
            }
        } else {
            token = Uuid.uuid();
            user = new User();
            user.setId(token);
            tokenToUserMap.put(token, user);
        }
        if (user == null) {
            loginResponseMessage = new LoginResponseMessage(Command.login_respnse, Status.C10008);
        } else {
            loginResponseMessage = new LoginResponseMessage(Command.login_respnse, Status.C10007, user);
        }
        if (loginResponseMessage == null || loginResponseMessage.getUser() == null) {
            log.info("登录失败, loginName:{}, password:{}", loginRequestMessage.getLoginname(), loginRequestMessage.getPassword());
            if (loginResponseMessage == null) {
                loginResponseMessage = new LoginResponseMessage(Command.login_respnse, Status.C10008);
            }
            loginResponseMessage.clear();
            PacketImpl loginRespPacket = new PacketImpl(Command.login_respnse, loginResponseMessage.toByte());
            io.bSend(asynchronousSocketChannelContext, loginRespPacket);
            io.remove(asynchronousSocketChannelContext, "loginName and token is incorrect");
            return null;
        }

        String userId = user.getId();


        sessionContext.getClient().setUser(user);
        io.bindUser(asynchronousSocketChannelContext, userId, userConfiguration.getMessageHelper().getBindListener());
        //初始化绑定或者解绑群组;
        bindUnbindGroup(asynchronousSocketChannelContext, user);

        loginResponseMessage.clear();
        PacketImpl loginRespPacket = new PacketImpl(Command.login_respnse, loginResponseMessage.toByte());
        return loginRespPacket;
    }
}
